package com.example.zhongshuishi.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.zhongshuishi.DemoConfig;
import com.example.zhongshuishi.entity.CustomerUserDetails;
import com.example.zhongshuishi.entity.PaymentNotifyDTO;
import com.example.zhongshuishi.entity.PaymentOrder;
import com.example.zhongshuishi.entity.StudentDto;
import com.example.zhongshuishi.mapper.StudentMapper;
import com.example.zhongshuishi.service.PaymentService;
import com.example.zhongshuishi.service.StudentService;
import com.example.zhongshuishi.utils.KSXJWTUtil;
import com.example.zhongshuishi.utils.KSXPostUtil;
import com.example.zhongshuishi.utils.OurpayKit;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author 鑫程垬纾
 * @version 1.0
 * @description TODO
 * @date 2025/3/29 12:27
 */
@RestController
@RequestMapping("/api")
public class PaymentController {
    Logger logger = LoggerFactory.getLogger(PaymentController.class);
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentMapper studentMapper;

    @RequestMapping(value = "/pay/callback", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<String> handlePaymentCallback(
            HttpServletRequest request,
            @ModelAttribute PaymentNotifyDTO notifyDTO) {
        // 1. 验证签名
        Map<String, Object> params = BeanUtil.beanToMap(notifyDTO);
        boolean verifyResult = OurpayKit.validSign(params, DemoConfig.priRsaKey, "RSA", null);


        boolean processResult = paymentService.processPaymentNotify(notifyDTO);

        return processResult ? ResponseEntity.ok("SUCCESS") : ResponseEntity.status(500).body("FAIL");
    }


    @PostMapping("/pay")
    public ResponseEntity<?> pay(@RequestBody StudentDto student) throws Exception {
        // 提前检查student是否为空
        if (student == null) {
            return ResponseEntity.badRequest().body("学生信息不存在");
        }

        //student.setId("100");
        student.setId(student.getId());

        // 生成订单号并保存订单
            student.setOrderNo("ZSS" + UUID.randomUUID().toString().replace("-", ""));
        student.setJiaocai("98");
        student.setApplication("2200");
        student.setPayment("2298");
        student.setCreatTime(new Timestamp(System.currentTimeMillis()));
        String payChannel = student.getPayChannel();
        student.setPayChannel(payChannel);
            studentService.addOrder(student);

            // 调用支付服务进行支付
            String qrCodeBase64 = paymentService.createPayment(student, student.getPayChannel());

            if (qrCodeBase64 != null && !qrCodeBase64.isEmpty()) {
                // 支付请求成功，更新支付状态
                student.setPaymentStatus("0");
                studentService.updateStudent(student);

                // 构造响应
                Map<String, Object> response = new HashMap<>();
                response.put("orderNo", student.getOrderNo());
                response.put("qrCode", qrCodeBase64);
                return ResponseEntity.ok().body(response);
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("生成二维码失败");
            }

    }

    @GetMapping("/pay/query")
    public ResponseEntity<?> queryPaymentOrder(@RequestParam String oderId) {
        try {
            Map<String, Object> result = paymentService.queryPaymentOrder(oderId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @GetMapping("/pay/order")
    public PageInfo payOrder( String stuId,String orderNo,Integer currPage,Integer pageSize) {
        try {
            List<PaymentOrder> paymentOrders = paymentService.selectByIdOrderNo(stuId,orderNo, currPage, pageSize);
            PageInfo pageInfo = new PageInfo( paymentOrders );
            return pageInfo;
        } catch (Exception e) {
            return null;
        }
    }

}


